#include "opencv.h"

void OPENCV::drawrevtangle()
{
    rectangle(this->m_mat,*(this->pre_pt),*(this->cur_pt),Scalar(255,0,0,0),2,8,0);
}

int OPENCV::imgshow(String imgName)
{
    int ret = 0;
    Mat img = imread(imgName,IMREAD_COLOR);
    if(img.empty()){
        cout<<imgName<<"is not exit"<<endl;
        return -1;
    }
    imshow(imgName,img);
    return 0;
}

void OPENCV::update(uint8_t *data)
{
    Mat m_mat;
    
    return;
}

bool OPENCV::isrunning()
{
    return this->m_run;
}

int OPENCV::start()
{
    int ret = 0;
    this->m_run = true;
    ret = pthread_create(&this->m_thread,NULL,opencv_handle_pthread,this);
    return ret;
}

int OPENCV::stop()
{
    int ret = 0;
    this->m_run = false;
    pthread_join(this->m_thread,NULL);
    return ret;
}

void mouseclick(int event, int x, int y, int flags, void *param)
{
    OPENCV* opencv = (OPENCV*)param;
    Mat tmp_1,tmp_2;
    if(event == EVENT_LBUTTONDOWN){
        //  左键按下
        *(opencv->pre_pt) = Point(x,y);
        cout<<"左键释放:"<<*(opencv->pre_pt)<<endl;
    }
    else if(event == EVENT_MOUSEMOVE && flags == 1){
        *(opencv->cur_pt) = Point(x,y);
        rectangle(opencv->m_mat,*(opencv->pre_pt),*(opencv->cur_pt),Scalar(255,255,0,0),1,8,0);
    }
    else if(event == EVENT_LBUTTONUP){
        *(opencv->cur_pt) = Point(x,y);
        rectangle(opencv->m_mat,*(opencv->pre_pt),*(opencv->cur_pt),Scalar(255,255,0,0),1,8,0);
        cout<<"左键释放:"<<*(opencv->cur_pt)<<endl;
    }
    else if(event == EVENT_RBUTTONDOWN){
        *(opencv->pre_pt) = Point(-1,-1);
        *(opencv->cur_pt) = Point(-1,-1);
    }
}

OPENCV::OPENCV()
{
    this->pre_pt = new Point(-1,-1);
    this->cur_pt = new Point(-1,-1);
    m_capture = new VideoCapture(0);    //从摄像头捕获视频
    namedWindow(this->m_windowname);
    setMouseCallback(this->m_windowname,mouseclick,this);
    if(!m_capture->isOpened()){
        cout<<"video is not exit"<<endl;
        return; 
    }
}

OPENCV::~OPENCV()
{
    pthread_join(this->m_thread,NULL);
    m_capture->release();
    delete m_capture;
}

void *opencv_handle_pthread(void *ptr)
{
    OPENCV *opencv = (OPENCV*)ptr;
    while(opencv->isrunning()){
        *(opencv->m_capture) >> opencv->m_mat;
        //rectangle(opencv->m_mat,*(opencv->pre_pt),*(opencv->cur_pt),Scalar(255,255,0,0),1,8,0);
        opencv->drawrevtangle();
        imshow(opencv->m_windowname,opencv->m_mat);   //  显示当前帧
        waitKey(30);
    }
    return nullptr;
}
